//-------------------------------------------
//兼容IE8的扩展设置值value的方法
$.fn.extend({
	val2: function(val) {
		if(val!=undefined){
			$(this).attr("value",val);
		}
		return $(this).attr("value")===undefined?"":$(this).attr("value");
	}
});
//兼容IE8的扩展时间转换的方法
$.extend({
	date_parse:function(value){
		var date=value;
		if(value===undefined){
			date="";
		}
		return Date.parse(date.replace(/-/g,"/"));
	}
});
//-------------------------------------------

$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';
$.ajaxSetup({complete:function(XHR, TS){
	var notAuditNum = 0;
	$.each($("#jqGrid2").jqGrid('getRowData'),function (i,d) {
		if(d.status=='待审核'){
			notAuditNum++;
		}
	})
	$("#b1").html("("+($("#jqGrid1").jqGrid('getRowData').length)+")");
	$("#b2").html("("+notAuditNum+'/'+($("#jqGrid2").jqGrid('getRowData').length)+")");
}});
$(document).ready(function () {

	$('#adjustTime').on('hide.zui.modal',function () {
		$("#date4").val('');
	});

	//设置时间控件的起始时间
	$("#date1").datetimepicker("setStartDate",dateTime ());
	$("#date2").datetimepicker("setStartDate",dateTime ());
	$("#date3").datetimepicker("setStartDate",dateTime ());

	//初始化调整时间框的默认提示时间
	$.placeholder();
	// $("#date1").attr("value",$("#registrationEndTime").html());
	// $("#date2").attr("value",$("#startDate").html());
	// $("#date3").attr("value",$("#quotationEndDate").html());
	$("#date1").val($("#registrationEndTime").html());
	$("#date2").val($("#startDate").html());
	$("#date3").val($("#quotationEndDate").html());


	var $body = $('body');
	var module = $body.data('moudle');
	var id = $body.data('id');
	//全局缓存
	var supplierList = {}; //邀请供应商

	$("#jqGrid1").jqGrid({
		url:ctx + '/rfqRequestState/querySupplierList',
		datatype: 'json',
		mtype: 'POST',
		rownumbers: true,
		colModel: [
			{
				label: '合格供应商代码',
				name: 'supplierCode',
				index: 'SUPPLIER_CODE',
				width: 18
			},
			{
				label: '供应商名称',
				name: 'supplierName',
				index: 'SUPPLIER_NAME',
				width: 50,
				formatter:selectFormatter
			},
			{
				label: '联系人',
				name: 'linkmanName',
				index: 'LINKMAN_NAME',
				width: 10

			},
			{
				label: '电话',
				name: 'linkmanTelphone',
				index: 'LINKMAN_TELPHONE',
				width: 17
			},
			{
				label: '保证金',
				name: 'assureFlag',
				index: 'ASSURE_FLAG',
				width: 10,
				formatter: function(cellValue){
					if( cellValue > 0 ){
						return '已缴纳' ;
					}else {
						return '未缴纳' ;
					}
				}
			},
			{
				label: '报价时间',
				name: 'quotationDate',
				index: 'QUOTATION_DATE',
				width: 25,
                formatter:quotationDateFormatter
			},
			{
				label: '报价情况',
				name: 'status',
				index: 'STATUS',
				width: 12,
				formatter: function(cellValue){
					if( 2 == cellValue || 3 == cellValue){
						return '已报价' ;
					}else if( 4 == cellValue ){
						return '已放弃' ;
					}else {
						return '未报价' ;
					}
				}
			},
			{
				label: 'IP地址',
				name: 'ip',
				index: 'IP',
				width: 18
			}
		],
		jsonReader: { //映射server端返回的字段
			root: "list",
			rows: "list",
			page: "pageNum",
			total: "pages",
			records: "total"
		},
		prmNames: {
			id: 'id'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
		},
		postData:{
			unifiedRfqNum:$("#unifiedRfqNum").val(),
			quotationRound:$("#quotationRound").val(),
			isFlag: $("#isFlag").val(),
			eventNumber : $("#eventNumber").val()
		},
		//viewrecords: true, // show the current page, data rang and total records on the toolbar
		//multiselect: true,
		width: 980,
		/*height: "100",*/
		rowNum: 100,
		rowList: [10, 20, 30],
		sortname: 'SUPPLIER_CODE',
		sortorder: 'asc',
		sortable:true,
/*        loadComplete:function () {
            //当前存在的数据加入缓存
            $.each($("#jqGrid1").jqGrid('getRowData'), function (i, d) {
                RFQ.d(d);
                var tmp = {};

                var value = d.supplierCode;
                if (!value) return true;
                tmp[value] = value;

                supplierList[value] = tmp;
                RFQ.d(supplierList);
            });
        }*/
	});


    function quotationDateFormatter(cellvalue, options,rawObject){
    	if (rawObject.status !=2 && rawObject.status !=3 && rawObject.status !=4 ){
    		return "";
		}else {
    		return cellvalue;
		}
	}
	function selectFormatter(cellvalue, options,rawObject) {
		var supplierCode = rawObject.supplierCode;
		var id = $("#requestId").val();
		//var unifiedRfqNum=$("#requestId").val();
		var url =ctx + "/rfqQuotation/getQuotationHistory?supplierNum=" + supplierCode+"&requestId=" + id;
		//return "<a class='blue' href='"+url+"' target='_blank'>合格</a>";
		//return rawObject.supplierName + "&nbsp;<a class='blue' href='"+url+"' target='_blank'>合格</a>";

		if( 0 == rawObject.isSupplier  ){
			return rawObject.supplierName + '&nbsp;<a class="label label-warning" href="javascript:;">待考察</a>';
		}else{
			return rawObject.supplierName  + '&nbsp;<a class="label label-success" href="javascript:;">合格</a>';
			//return rawObject.supplierName  + '&nbsp;<a class="label label-success" href="'+url+'">合格</a>';
		}
	}

	var colModelM;
	if ($("#testPriv").length>0){
		colModelM=[
			{
				label: '合格供应商代码',
				name: 'supplierCode',
				index: 'SUPPLIER_CODE',
				width: 18
			},
			{
				label: '系统主键',
				name: 'pasId',
				index: 'PAS_ID',
				width: 1,
				hidden: true
			},
			{
				label: '是否为合格供应商',
				name: 'isSupplier',
				index: 'IS_SUPPLIER',
				width: 1,
				hidden: true
			},
			{
				label: '供应商名称',
				name: 'supplierName',
				index: 'SUPPLIER_NAME',
				width: 42,
				formatter: function(cellvalue, options,rawObject){
					if( 0 == rawObject.isSupplier  ){
						return rawObject.supplierName + '&nbsp;<a class="label label-warning " href="javascript:;">待考察</a>';
					}else{
						return rawObject.supplierName  + '&nbsp;<a class="label label-success " href="javascript:;">合格</a>';
					}
				}
			},
			{
				label: '联系人',
				name: 'linkmanName',
				index: 'LINKMAN_NAME',
				width: 10
			},
			{
				label: '电话',
				name: 'linkmanTelphone',
				index: 'LINKMAN_TELPHONE',
				width: 17
			},
			{
				label: '报名时间',
				name: 'answerTime',
				index: 'ANSWER_TIME',
				width: 25
			},
			{
				label: '审批时间',
				name: 'approvalTime',
				index: 'APPROVAL_TIME',
				width: 25
			},
			{
				label: '状态',
				name: 'status',
				index: 'STATUS',
				width: 10,
				formatter: function(cellValue){
					if( 0 == cellValue ){
						return '待审核' ;
					}else if( 1 == cellValue ){
						return '通过' ;
					}else if( 2 == cellValue ){
						return '驳回' ;
					}
				}
			},
			{
				width: 15,
				label: '操作',
				name: 'id',
				index: 'ID',
				formatter: actFormatter
			}
		];
	}else{
		colModelM=[
			{
				label: '合格供应商代码',
				name: 'supplierCode',
				index: 'SUPPLIER_CODE',
				width: 18
			},
			{
				label: '系统主键',
				name: 'pasId',
				index: 'PAS_ID',
				width: 1,
				hidden: true
			},
			{
				label: '是否为合格供应商',
				name: 'isSupplier',
				index: 'IS_SUPPLIER',
				width: 1,
				hidden: true
			},
			{
				label: '供应商名称',
				name: 'supplierName',
				index: 'SUPPLIER_NAME',
				width: 42,
				formatter: function(cellvalue, options,rawObject){
					if( 0 == rawObject.isSupplier  ){
						return rawObject.supplierName + '&nbsp;<a class="label label-warning " href="javascript:;">待考察</a>';
					}else{
						return rawObject.supplierName  + '&nbsp;<a class="label label-success " href="javascript:;">合格</a>';
					}
				}
			},
			{
				label: '联系人',
				name: 'linkmanName',
				index: 'LINKMAN_NAME',
				width: 10
			},
			{
				label: '电话',
				name: 'linkmanTelphone',
				index: 'LINKMAN_TELPHONE',
				width: 17
			},
			{
				label: '报名时间',
				name: 'answerTime',
				index: 'ANSWER_TIME',
				width: 25
			},
			{
				label: '审批时间',
				name: 'approvalTime',
				index: 'APPROVAL_TIME',
				width: 25
			},
			{
				label: '状态',
				name: 'status',
				index: 'STATUS',
				width: 10,
				formatter: function(cellValue){
					if( 0 == cellValue ){
						return '待审核' ;
					}else if( 1 == cellValue ){
						return '通过' ;
					}else if( 2 == cellValue ){
						return '驳回' ;
					}
				}
			}
		];

	}

	$("#jqGrid2").jqGrid({
		url:ctx + '/rfqRequestState/queryPreauditSupplier',
		datatype: 'json',
		mtype: 'POST',
		rownumbers: true,
		colModel: colModelM,
		jsonReader: { //映射server端返回的字段
			root: "list",
			rows: "list",
			page: "pageNum",
			total: "pages",
			records: "total"//在Controller设置该变量将查询的Conut数给它
		},
		prmNames: {
			id: 'id'//请求参数映射，如默认参数为id，实际参数为myId则可在此映射
		},
		postData:{
			unifiedRfqNum:$("#unifiedRfqNum").val()
		},
		//viewrecords: true, // show the current page, data rang and total records on the toolbar
		//multiselect: true,
		width: 980,
		rowNum: 10,
		rowList: [10, 20, 30],
		/*height: "100",*/
		sortname: 'SUPPLIER_CODE',
		sortorder: 'asc',
		sortable:true
		//pager: "#jqGridPager",
		//caption: "供应商列表"

	});

	//function formatTitle(cellValue, options, rowObject) {
	//    return cellValue.substring(0, 50) + "...";
	//};
	$("#jqGrid1").jqGrid('setLabel', 0,"序号");
	$("#jqGrid2").jqGrid('setLabel', 0,"序号");
	function actFormatter(cellvalue, options, rawObject) {
			var status = rawObject.status;
		if (rType == '11' || rType == '12'){
			var examinationBtn = '<span class="btn btn-sm btn-info" onclick="checkedToSee(\'' + rawObject.supplierCode + '\')"><i class="icon icon-check-sign"></i>查看</span>';
		} else if(status == '0'){
			var examinationBtn = '<span class="btn btn-sm btn-info" onclick="examinationAndApproval(\'' + rawObject.pasId + '\')"><i class="icon icon-check-sign"></i>审批</span>';
		} else if(status == '2'){
			var examinationBtn = '<span class="btn btn-sm btn-info" onclick="checkedToSee(\'' + rawObject.supplierCode + '\')"><i class="icon icon-check-sign"></i>查看</span>';
		}else if(status == '1'){
			var examinationBtn = '<span class="btn btn-sm btn-info" onclick="checkedToSee(\'' + rawObject.supplierCode + '\')"><i class="icon icon-check-sign"></i>查看</span>';
		}
		return examinationBtn;
	};






	//邀请供应商
	(function(){

		var jqGrid = null;
		var sdata = [];
		var $supplistModal = $('#supplistModal');
		var $form = $supplistModal.find('form');
		$supplistModal.on('shown.zui.modal',function(){
            getAttData("#jqGridsup", "#jqGridPagersup");
		});

		function getAttData(grid,page){
			//启用内存分页
			jqGrid = RFQ.jqGrid(grid).init({
				datatype:"local",
				multiselect: true,
				colModel: [
					{
						name: 'companyId',
						index: 'companyId',
						key: true,
						hidden: true
					},
					{
						name: 'companyId',
						index: 'companyId',
						hidden: true
					},
                    {
                        name: 'isBindWechat',
                        index: 'isBindWechat',
                        hidden: true
                    },
					{
						label: '合格供应商代码',
						name: 'supplierCode',
						width: 20,
					},
					{
						label: '供应商名称',
						name: 'supplierName',
						width: 20,
					},
					{
						label: '所属类别',
						name: 'type',
						width: 20,
					},
					{
						label: '供应商等级',
						name: 'deviceDealerGrade',
						width: 20,
					},
					{
						label: '联系人',
						name: 'linkmanName',
						width: 20,
					},
					{
						label: '联系电话',
						name: 'linkmanTelphone',
						width: 20
					}
				],
				pager: page,
                height:360,
				rowNum: 20,//每页显示记录数
				rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
			});
			$.post(ctx+'/rfqSupplierListNew/rfqSupplierListListNew',{}, function (data) {
				sdata = (data.list||[]).filter(function (item) {
					return !supplierList[item.companyId];
				});
				$form[0].reset();
                $.placeholder();
				jqGrid.loadLocal(sdata);
				//重新填充输入框提示文字
                $.placeholder();
			},'json')
		}

		$("#btnSearch").click(function () {
			var validJson = {};
			$form.find(':text,select').not('.phcolor').each(function () {
				this.value && (validJson[this.name] = this.value);
			});
			var searchData = sdata.filter(function (item) {
				var isValid = true;
				for(var key in validJson){
					if(!isValid) return false;
					if(key == 'supplierName' || key == 'supplierCode' || key == 'deviceDealerGrade'){
						isValid =item[key] &&  ~item[key].indexOf(validJson[key]);//模糊匹配
					}else{
						isValid = (item[key] == validJson[key]);
					}
				}
				return isValid;
			});
			jqGrid.loadLocal(searchData);
		});

		//DOM操作
		var rowTmp = '<tr><td>{index}</td> <td>{supplierCode}</td> <td>{supplierName}</td> <td>{linkmanName}</td><td>{linkmanTelphone}</td> <td>未绑定</td> <td><a class="order-del-btn" data-id="{companyId}"><i class="red icon icon-trash"></i>&nbsp; 删除</a></td> </tr>';
		var rowIndex = 0;



		$('#auditModa1').on('click','.js-confirm', function () {
			var rows = $('#jqGridsup').jqGrid("getGridParam", "selarrrow");
			var renderHTML = [];
			var flag=true;
			var quotationNames=[];
			var signUpName=[];
			var type = 0;
			$.each(rows,function(i,r){
				if(supplierList[r]) return true;
				var rowData = $('#jqGridsup').jqGrid('getRowData',r);//获取选中行的数据（单行）
				$('td[aria-describedby=jqGrid1_supplierCode]').each(function(i,d){
					if( rowData.supplierCode ===$(d).text()){
						quotationNames.push(rowData.supplierName);
						flag= false;
						//return flag;
					}
				});
				$('td[aria-describedby=jqGrid2_supplierCode]').each(function(i,d){
					if( rowData.supplierCode ===$(d).text()){
						signUpName.push(rowData.supplierName);
						flag= false;
						//return flag;
					}
				});
				rowData.index = rowIndex+1;
				rowIndex ++;
			});
			if(quotationNames.length>0 && signUpName.length>0){
				type = 3;
			}else if(quotationNames.length>0 && signUpName.length===0){
				type = 2;
			}else if(signUpName.length>0 && quotationNames.length===0){
				type = 1;
			}
			if(!flag && 3 === type){
            	$.zui.messager.show("'"+quotationNames+"'已在报价供应商列表中！<br/>"+"'"+signUpName+"'已在报名供应商列表中！", {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
            	return;
            }else if(!flag && 2 === type){
            	$.zui.messager.show("'"+quotationNames+"'已在报价供应商列表中！", {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
            	return;
            }else if(!flag && 1 === type){
            	$.zui.messager.show("'"+signUpName+"'已在报名供应商列表中！", {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
            	return;
            }
			//确认提交
			var selAudit = $('#approvalCode').val();
			var procDefType = selAudit.split(",")[1];
			if(selAudit != 0) {   //选择审批
				if (procDefType == 2) {   //灵活流程
					$('#auditModa1').modal('hide');
					$('#myRole').modal('show');
					return;
				} else {
					var $confirmBtn = $('#auditModa1').find('.modal-footer .btn-primary');
					$confirmBtn.attr('disabled', true);
					postforData([]);
				}
			}else {
				var $confirmBtn = $('#auditModa1').find('.modal-footer .btn-primary');
				$confirmBtn.attr('disabled', true);
				postforData([]);
			}
			$.each(rows,function(i,r){
				if(supplierList[r]) return true;
				var rowData = $('#jqGridsup').jqGrid('getRowData',r);//获取选中行的数据（单行）
				rowData.index = rowIndex+1;
				renderHTML.push(rowTmp.format(rowData));
				rowIndex ++;
				//数据加入缓存
				supplierList[rowData.companyId] = rowData;
				//addSupplist (rowData);
			});
			$('#supplierListTable tbody').append(renderHTML.join(''));
			$('#supplistModal').modal('hide');

		});

		//function addSupplist (d){
		//	d.requestId=$("#id").val();
		//	d.unifiedRfqNum = $("#unifiedRfqNum").val();
		//	d.approvalCode = $("#approvalCode").val();
		//	$.ajax({
		//		type: "POST",
		//		url:ctx + '/rfqRequestState/addSupplist',
		//		async:false,
		//		data:d,
		//		success: function (data) {
		//			if(data.status=='failed'){
         //               $('#auditModa1').modal('hide');
         //              RFQ.warn(data.msg);
		//			}else{
         //               resetSeq();
         //               window.location.reload();
		//			}
		//		}
		//	});
		//};

		//删除
		$('#supplierListTable').on('click','.order-del-btn',function(){
			var id = $(this).data("id");
			$(this).parent().parent("tr").remove();
			//从缓存里面删除
			delete supplierList[id];
			rowIndex > 0 && rowIndex--;
			resetSeq();
		});



	})();

});

//ajax提交方法
function postforData(rowDataLists){
	var rows = $('#jqGridsup').jqGrid("getGridParam", "selarrrow");
	var rowSuppDatas = new Array();
	$.each(rows,function(i,r){
		var rowData = $('#jqGridsup').jqGrid('getRowData',r);//获取选中行的数据（单行）
		rowData.requestId=$("#id").val();
		rowData.unifiedRfqNum = $("#unifiedRfqNum").val();
		rowData.approvalCode = $("#approvalCode").val();
		rowSuppDatas.push(rowData);
	});
	$.ajax({
		type: "POST",
		url:ctx + '/rfqRequestState/addSupplist',
		async:false,
		data:{
			requestId: $("#id").val(),
			approvalCode: $("#approvalCode").val(),
			rowSuppDatas: JSON.stringify(rowSuppDatas),
			rowDataLists: JSON.stringify(rowDataLists)
		},
		success: function (data) {
			if(data.status=='failed'){
				$('#auditModa1').modal('hide');
				RFQ.warn(data.msg);
                var $confirmBtn = $('#auditModa1').find('.modal-footer .btn-primary');
                $confirmBtn.removeAttr("disabled");
			}else{
				$('#auditModa1').modal('hide');
				// resetSeq();
				$("#jqGrid1").trigger('reloadGrid');
				window.location.reload();
			}
		}
	});
}

//重新设置序号
function resetSeq(){
	var $tds = $('#supplierListTable tbody').find('tr td:first-child');
	$tds.each(function (i,el) {
		$(this).html(i+1);
	});
}

function examinationAndApproval(pasId) {
	var requestId=$("#id").val();
	var aa = window.open();
	var url = ctx+"/rfqPreauditSupplier/auditInit?id=" + pasId+"&requestNum="+requestId;
	aa.location.href = url ;
}

function checkedToSee(supplierCode){
	var unifiedRfqNum = $("#unifiedRfqNum").val();
	var aa = window.open();
	var url = ctx + "/rfqPreauditSupplier/preauditSupplierDetailByAudit?unifiedRfqNum=" + unifiedRfqNum+"&supplierCode=" + supplierCode;
	aa.location.href = url ;
}

function checkedToAdopt(pasId){
	var aa = window.open();
	var url = ctx+"/rfqPreauditSupplier/auditHistoryDetail?pasId="+pasId;
	aa.location.href = url ;
}

function dateTime (){
	var date = "";
	$.ajax({
		type: "POST",
		async:false,
		url:ctx + '/common/getNowTime',
		data: {
		},
		success: function (data) {
			date =  new Date(data*1000);
		}
	});
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	var hours = date.getHours();
	var minutes = date.getMinutes();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	if (hours >= 0 && hours <= 9) {
		hours = "0" + hours;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}
	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
		+ " " + hours + seperator2 + minutes ;
	return currentdate;
}

//撤销询单
function revoke(){
	if( $("#pubEndMemo").val().length == 0){
		$.zui.messager.show('sorry，请填写撤销原因！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
		return;
	}
	if($("#pubEndMemo").val().length > 2000){
		$.zui.messager.show('撤销原因不可超过2000个字！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
		return;
	}
	$.ajax({
		type: "POST",
		url:ctx + '/rfqRequestState/revocationOfRequest',
		data: {
			extendField4:$("#extendField4  option:selected").val(),
			pubEndMemo:$("#pubEndMemo").val(),
			unifiedRfqNum:$("#unifiedRfqNum").val(),
			id:$("#id").val()
		},
		success: function (data) {
			if (data.status == 'success') {
				location.href = $("#contextPath").val() + "/rfqRequest/init";
			} else {
				$.zui.messager.show('sorry,系统出错了！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
			}
		}
	});
}

//控件框获取系统当前时间
function nowTime (num){
	switch(num) {
		case 1:
			if (!$("#date1").prop("disabled")) {
					$("#date1").val(dateTime());
				//如果报名时间大于报价时间则将值设定与报价一致
				//var date1 = $.date_parse($("#date1").val());
				//var date3 = $.date_parse($("#quotationEndDate").html());
				//if($("#date3").val()!="" ){
				//	if(date1 > $.date_parse($("#date3").val())){
				//		$("#date1").val2($("#date3").val());
				//	}
				//}else{
				//	if ( date1 > date3 ){
				//		$("#date1").val2($("#quotationEndDate").html());
				//	}
				//}
			}
			break;
		case 2:
			if (!$("#date2").prop("disabled")) {
					$("#date2").val(dateTime());
			}
			break;
		case 3:
			if (!$("#date3").prop("disabled")) {
					$("#date3").val(dateTime());
				var registrationEndTime = $.date_parse($("#registrationEndTime").html());
				var date3 = $.date_parse($("#date3").val());
				if(registrationEndTime > date3){
					$("#date1").val(dateTime());
				}
			}
	}
}

//指定时间清除控件框内的值
function specifiedTime(num){
	switch(num) {
		case 1:
			if (!$("#date1").prop("disabled")) {
					$("#date1").removeAttr("disabled");
					$("#date1").val("");
			}
			break;
		case 2:
			if (!$("#date2").prop("disabled")) {
					$("#date2").removeAttr("disabled");
					$("#date2").val("");
			}
			break;
		case 3:
			if (!$("#date3").prop("disabled")) {
					$("#date3").removeAttr("disabled");
					$("#date3").val("");
			}
	}
};

//时间输入做正则验证
function validateTime(time){
	var flg=false;
	var vaildate=/^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\s([0-1]?[0-9]|2[0-3]):([0-5][0-9])$/;
	 if(vaildate.test(time)){
	  flg=true;
	return flg;
	 }else{
		return flg;
	 };
}

//检查时间是否可以调整
function checkTime (){
	$.placeholder();
	// $("#date1").attr("value",$("#registrationEndTime").html());
	// $("#date2").attr("value",$("#startDate").html());
	// $("#date3").attr("value",$("#quotationEndDate").html());
	$("#date1").val($("#registrationEndTime").html());
	$("#date2").val($("#startDate").html());
	$("#date3").val($("#quotationEndDate").html());

	var registrationEndTime = $.date_parse($("#registrationEndTime").html());
	var startDate = $.date_parse($("#startDate").html());
	var quotationEndDate = $.date_parse($("#quotationEndDate").html());
	var now = $.date_parse(dateTime());

	if('报名中' === $("#nowState").html() || '待报价' === $("#nowState").html() || '报价中' === $("#nowState").html() || '竞价中' === $("#nowState").html()){
		if(registrationEndTime <= now || "公开寻源" !=$("#publicBiddingFlag").html() || $("#quotationRound").val() > 0){
			$("#dropdownMenu1").addClass("disabled");
		//	$("#date1").val("");
			$("#date1").attr("disabled","true");
		}
	}
	if(startDate <= now ){
		$("#dropdownMenu2").addClass("disabled");
	//	$("#date2").val("");
		$("#date2").attr("disabled","true");
	}
	if(quotationEndDate <= now ){
		$("#dropdownMenu3").addClass("disabled");
		$("#date3").val("");
		$("#date3").attr("disabled","true");
	}
}

//更新时间请求
function updateTime (){


	var date1 = $.date_parse($("#date1").val());


	var date2 = $.date_parse($("#date2").val());


	var date3 = $.date_parse($("#date3").val());

	var registrationEndTime = $.date_parse($("#registrationEndTime").html());
	var startDate = $.date_parse($("#startDate").html());
	var quotationEndDate = $.date_parse($("#quotationEndDate").html());
	var now = $.date_parse(dateTime());

	if(!$("#date1").prop("disabled") && !isNaN(date1) ){
		if( validateTime( $("#date1").val() ) ){
			if( date1 < now ){
				$.zui.messager.show('sorry，修改后报名截止时间早于系统当前时间', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else{
			$.zui.messager.show('sorry，时间格式不正确，请注意检查闰年和特殊月份天数或核对时间格式  正确的格式如:2000-01-01 00:00', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
			return;
		}
	}

	if(!$("#date2").prop("disabled") && !isNaN(date2)){
		if(validateTime($("#date2").val())){
			if( date2 < now ){
				$.zui.messager.show('sorry，修改后时间早于系统当前时间', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else{
			$.zui.messager.show('sorry，时间格式不正确，请注意检查闰年和特殊月份天数或核对时间格式  正确的格式如:2000-01-01 00:00', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
			return;
		}
	}

	if(!isNaN(date3)){
		if(validateTime($("#date3").val())){
			if( date3 < now ){
				$.zui.messager.show('sorry，修改后时间早于系统当前时间', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else{
			$.zui.messager.show('sorry，时间格式不正确，请注意检查闰年和特殊月份天数或核对时间格式  正确的格式如:2000-01-01 00:00', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
			return;
		}
	}

	if( date3 > 0 &&  date3 != null && date3 != undefined ){
		if( date2 > 0 &&  date2 != null && date2 != undefined){
			if( date2 > date3 ){
				$.zui.messager.show('sorry，报价截止时间不能早于报价开始时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else {
			if( startDate > date3 ){
				$.zui.messager.show('sorry，报价截止时间不能早于报价开始时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}
	}else{
		if(date2 > 0 &&  date2 != null && date2 != undefined ){
			if( date2 > quotationEndDate){
				$.zui.messager.show('sorry，报价截止时间不能早于报价开始时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else{
			if( startDate > quotationEndDate){
				$.zui.messager.show('sorry，报价截止时间不能早于报价开始时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}
	}

	if( date3 > 0 &&  date3 != null && date3 != undefined ){
		if( date1 > 0 &&  date1 != null && date1 != undefined){
			if( date1 > date3 ){
				$.zui.messager.show('sorry，报名截止时间不能晚于报价截止时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else {
			if( registrationEndTime > date3 ){
				$.zui.messager.show('sorry，报名截止时间不能晚于报价截止时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}
	}else{
		if(date1 > 0 &&  date1 != null && date1 != undefined ){
			if( date1 > quotationEndDate){
				$.zui.messager.show('sorry，报名截止时间不能晚于报价截止时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}else{
			if( registrationEndTime > quotationEndDate){
				$.zui.messager.show('sorry，报名截止时间不能晚于报价截止时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
				return;
			}
		}
	}
  if($("#date1").val() !="" || $("#date2").val() !="" || $("#date3").val() !=""){
	  if( $("#date4").val().length == 0){
		  $.zui.messager.show('sorry，请填写修改原因！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
		  return;
	  }
  }else{
	  $.zui.messager.show('sorry，请填入修改后的时间！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
	  return;
  }

	if( $("#date4").val().length > 2000){
		$.zui.messager.show('修改原因字数不可超过2000字！', {placement: 'center', type: 'warning', icon: 'icon-exclamation-sign'});
		return;
	}
	//报名截止时间锁定时,报名截止时间提交时置为空
	if('报名中' === $("#nowState").html() || '待报价' === $("#nowState").html() || '报价中' === $("#nowState").html() ){
		if($.date_parse($("#registrationEndTime").html()) <= $.date_parse(dateTime()) || "公开寻源" !=$("#publicBiddingFlag").html() || $("#quotationRound").val() > 0){
			$("#date1").val("");
		}
	}
	//报价开始时间锁定时,报价开始时间提交时设置为空
	if($.date_parse($("#startDate").html()) <= $.date_parse(dateTime()) ){
		$("#date2").val("");
	}
	//报价截止时间置为空
	if($.date_parse($("#quotationEndDate").html()) <= $.date_parse(dateTime()) ){
		$("#date3").val("");
	}
	$.ajax({
		type: "POST",
		url:ctx + '/rfqRequestState/updateTime',
		data: {
			registrationEndTime: $("#date1").val(),
			startDate:$("#date2").val(),
			quotationEndDate:$("#date3").val(),
			remarks:$("#date4").val(),
			unifiedRfqNum:$("#unifiedRfqNum").val()
		},
		success: function (data) {
			if (data.status == 'success') {
				//如果是立即结束返回到询单管理页
				/*if($("#date1").val() <= dateTime () ||$("#date2").val() <= dateTime ()|| $("#date3").val() <= dateTime ()){*/
					if($("#date1").val() == dateTime() ||$("#date2").val() == dateTime()|| $("#date3").val() == dateTime()){
					window.location.href=ctx+"/rfqRequest/init";
				}else{
					window.location.reload();
				}
			} else {
				$.zui.messager.show('sorry，时间修改失败！', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
			}
		}
	});
}
function bidOpening (){
	$.ajax({
		type: "POST",
		url:ctx + '/rfqRequestState/bidOpening',
		data: {
			unifiedRfqNum:$("#unifiedRfqNum").val()
		},
		success: function (data) {
			window.location.href=ctx+"/designateResult/init?unifiedRfqNum="+data;
		}
	});
}function opening (){
	var type=$("#type").val();
	if(type!='7'){
		$.zui.messager.show('sorry，竞价单当前不为开标状态，不可执行此操作', {placement: 'center', type: 'danger', icon: 'icon-exclamation-sign'});
	    return false;
	};
	$.ajax({
		type: "POST",
		url:ctx + '/designateContract/bidOpening',
		data: {
			unifiedRfqNum:$("#unifiedRfqNum").val(),
			requestId:$("#id").val()
		},
		success: function (data) {
			window.location.href=ctx+"/designateContract/init?unifiedRfqNum="+data;
		}
	});
}

function resetValues1(){
	$("#extendField4 option").eq(0).attr("selected",true);
	$("#pubEndMemo").val("");
}


function getAttData2(grid,page){//供应商等级选择未认证
    //全局缓存
    var supplierList = {}; //邀请供应商
    var jqGrid = null;
    var sdata = [];
    var $supplistModal = $('#supplistModal');
    var $form = $supplistModal.find('form');

    //启用内存分页
    jqGrid = RFQ.jqGrid(grid).init({
        datatype:"local",
        multiselect: true,
        colModel: [
            {
                name: 'companyId',
                index: 'companyId',
                key: true,
                hidden: true
            },
            {
                name: 'companyId',
                index: 'companyId',
                hidden: true
            },
            {
                name: 'isBindWechat',
                index: 'isBindWechat',
                hidden: true
            },
            {
                label: '合格供应商代码',
                name: 'supplierCode',
                width: 20,
            },
            {
                label: '供应商名称',
                name: 'supplierName',
                width: 20,
            },
            {
                label: '所属类别',
                name: 'type',
                width: 20,
            },
            {
                label: '供应商等级',
                name: 'deviceDealerGrade',
                width: 20,
            },
            {
                label: '联系人',
                name: 'linkmanName',
                width: 20,
            },
            {
                label: '联系电话',
                name: 'linkmanTelphone',
                width: 20
            }
        ],
        pager: page,
        height:360,
        rowNum: 20,//每页显示记录数
        rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
    });
    $.post(ctx+'/rfqSupplierListNew/rfqSupplierListListNew',{}, function (data) {
        sdata = (data.list||[]).filter(function (item) {
            return (!supplierList[item.companyId] && item.deviceDealerGrade =="未认证");
        });
		//过滤模糊搜索
        var validJson = {};
        $form.find(':text,select').not('.phcolor').each(function () {
            this.value && (validJson[this.name] = this.value);
        });
        sdata = sdata.filter(function (item) {
            var isValid = true;
            for(var key in validJson){
                if(!isValid) return false;
                if(key == 'supplierName' || key == 'supplierCode' || key == 'deviceDealerGrade'){
                    isValid =item[key] &&  ~item[key].indexOf(validJson[key]);//模糊匹配
                }else{
                    isValid = (item[key] == validJson[key]);
                }
            }
            return isValid;
        });
        jqGrid.loadLocal(sdata);
        //重新填充输入框提示文字
        $.placeholder();
    },'json')
}


function getAttData3(grid,page){//供应商等级选择已认证
    //全局缓存
    var supplierList = {}; //邀请供应商
    var jqGrid = null;
    var sdata = [];
    var $supplistModal = $('#supplistModal');
    var $form = $supplistModal.find('form');
    //启用内存分页
    jqGrid = RFQ.jqGrid(grid).init({
        datatype:"local",
        multiselect: true,
        colModel: [
            {
                name: 'companyId',
                index: 'companyId',
                key: true,
                hidden: true
            },
            {
                name: 'companyId',
                index: 'companyId',
                hidden: true
            },
            {
                name: 'isBindWechat',
                index: 'isBindWechat',
                hidden: true
            },
            {
                label: '合格供应商代码',
                name: 'supplierCode',
                width: 20,
            },
            {
                label: '供应商名称',
                name: 'supplierName',
                width: 20,
            },
            {
                label: '所属类别',
                name: 'type',
                width: 20,
            },
            {
                label: '供应商等级',
                name: 'deviceDealerGrade',
                width: 20,
            },
            {
                label: '联系人',
                name: 'linkmanName',
                width: 20,
            },
            {
                label: '联系电话',
                name: 'linkmanTelphone',
                width: 20
            }
        ],
        pager: page,
        height:360,
        rowNum: 20,//每页显示记录数
        rowList: [20,30, 50, 100],//用于改变显示行数的下拉列表框的元素数组。
    });
    $.post(ctx+'/rfqSupplierListNew/rfqSupplierListListNew',{}, function (data) {
         sdata = (data.list||[]).filter(function (item) {
                return (!supplierList[item.companyId] && item.deviceDealerGrade =="已认证");

        });
        var validJson = {};
        $form.find(':text,select').not('.phcolor').each(function () {
            	this.value && (validJson[this.name] = this.value);
        });
        sdata = sdata.filter(function (item) {
            var isValid = true;
            for(var key in validJson){
                if(!isValid) return false;
                if(key == 'supplierName' || key == 'supplierCode' || key == 'deviceDealerGrade'){
                    isValid =item[key] &&  ~item[key].indexOf(validJson[key]);//模糊匹配
                }else{
                    isValid = (item[key] == validJson[key]);
                }
            }
            return isValid;
        });
       // $form[0].reset();
        jqGrid.loadLocal(sdata);
        //重新填充输入框提示文字
        $.placeholder();
    },'json')
}